﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using MedicalAdviser.Controllers;
using MedicalAdviser.Controllers.WsValidation;
using MedicalAdviser.DAL;
using MedicalAdviser.Portable.DataTypes;
using MedicalAdviser.Portable.DataTypes.DomainObjects;
using MedicalAdviser.Portable.DataTypes.WsTypes;
using MedicalAdviser.Interfaces.WsInterfaces;
using Action = MedicalAdviser.Portable.DataTypes.WsTypes.Action;

namespace MedicalAdviser.RestService
{
    /*  TO DO
        Ainda faltam implementar algumas operação
     * 1. Pesquisa com todos os parametros e com a paginação feita, para disponibilizar duas operação ao user uma para a query e outra que vai dando os medicamentos
     * 2. Dar a variação do preco do medicamento nos ultuimos anos
     * 3. Mostrar os medicamentos subsititutos por ordem de recomendação
     * 4. Por fim falta ver a questão do login, como vou fazer a validação do token se chamada directa ao serviço ou guardar o tamanho na BD;
     * 
     */
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "AdviserOperations" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select AdviserOperations.svc or AdviserOperations.svc.cs at the Solution Explorer and start debugging.
    public class AdviserOperations : IAdviserOperations
    {
       

        //public ServiceOut<SearchResult> QuickSearch(SearchDrug search)
        //{
        //    ServiceOut<SearchResult> _result = new ServiceOut<SearchResult>();
        //    try
        //    {
        //        if(search == null )
        //            search = new SearchDrug()
        //                {
        //                    GenericSearch = "Vitaminas"
        //                };


        //        SearchDrug TInput = new SearchDrug()
        //        {
        //            GenericSearch = search.GenericSearch
        //        };

        //        DAL.SearchController cena = new DAL.SearchController();
        //       _result.Value.Results = cena.QuickSearch(search);

        //        return _result;

        //    }
        //    catch (Exception ex)
        //    {

        //        throw ex;
        //    }
        //}

        #region Implementation of IAdviserOperations

        public string DoWork()
        {
            ActionManager.MakeThisAysnc();

            return "Veio do servidor as " + DateTime.Now ;

        }

        public string GetMyName(string id)
        {
            throw new NotImplementedException();
        }

        public ServiceOut<Auth> Login(Auth auth)
        {
            throw new NotImplementedException();
        }

        public ServiceOut<Auth> Logout(Auth auth)
        {
            throw new NotImplementedException();
        }

        public ServiceOut<List<CdoDrug>> QuickSearch(SearchDrug tSearch)
        {
            MedicalAdviser.DAL.SelectOperation op =  new SelectOperation();

            ServiceOut<List<CdoDrug>> ret = new ServiceOut<List<CdoDrug>>();

            //ret.Value = op.QuickSearch(tSearch);

            //DrugContext.SaveContext();

            return ret;
        }

        /// <summary>
        /// Falta ainda implementar depois de criar ao proxy para ver a melhor maneira de fazer a 
        /// paginação
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        public ServiceOut<SearchResult> RefinedSearch(SearchDrug search)
        {
            throw new NotImplementedException();
        }

        public ServiceOut<int> ReccomendDrug(AppInteration tInput)
        {
            try
            {
                //Verify the entry parameter
                ResquestIntegretyController.VerifyActionParameter(tInput);

                if (tInput.Action != Action.RecommendDrug)
                    throw new Exception(
                        String.Format("Action code is wrong, request code action is wrong for this operation. Make the request whit the right action code."));

                int ret = MedicalAdviser.Controllers.ActionManager.SaveAction(tInput);
                return new ServiceOut<int>()
                {
                    Error = false,
                    InnerMessage = "Sucess this action is registered!",
                    Value = ret
                };

            }
            catch (Exception ex)
            {
                return new ServiceOut<int>()
                {
                    Error = true,
                    InnerMessage = ex.Message.ToString(),
                    Value = -1
                };
            }

        }

        public ServiceOut<int> SearchKeyword(AppInteration tInput)
        {
            try
            {
                //Verify the entry parameter
                ResquestIntegretyController.VerifyActionParameter(tInput);

                if (tInput.Action != Action.Keyword)
                    throw new Exception(
                        String.Format("Action code is wrong, request code action is wrong for this operation. Make the request whit the right action code."));

                int ret = MedicalAdviser.Controllers.ActionManager.SaveAction(tInput);
                return new ServiceOut<int>()
                {
                    Error = false,
                    InnerMessage = "Sucess this action is registered!",
                    Value = ret
                };

            }
            catch (Exception ex)
            {
                return new ServiceOut<int>()
                {
                    Error = true,
                    InnerMessage = ex.Message.ToString(),
                    Value = -1
                };
            }
        }

        public ServiceOut<int> ViewDrug(AppInteration tInput)
        {
            try
            {
                //Verify the entry parameter
                ResquestIntegretyController.VerifyActionParameter(tInput);

                if (tInput.Action != Action.ViewDrug)
                    throw new Exception( String.Format("Action code is wrong, request code action is wrong for this operation. Make the request whit the right action code."));

                /* Operation Code */
                int ret = MedicalAdviser.Controllers.ActionManager.SaveAction(tInput);
                return new ServiceOut<int>()
                           {
                               Error = false,
                               InnerMessage = "Sucess this action is registered!",
                               Value = ret
                           };
            }
            catch (Exception ex)
            {
                return new ServiceOut<int>()
                           {
                               Error = true,
                               InnerMessage = ex.Message.ToString(),
                               Value = -1
                           };
            }
        }

        public ServiceOut<CdoDrug> OpenDrug(AppInteration tInput)
        {
            try
            {
                //Verify the entry parameter
                ResquestIntegretyController.VerifyActionParameter(tInput);

                if (tInput.Action != Action.OpenDrug)
                    throw new Exception(String.Format("Action code is wrong, request code action is wrong for this operation. Make the request whit the right action code."));

                CdoDrug drug = MedicalAdviser.Controllers.DrugOperations.GetDrugInformation(tInput);
                return new ServiceOut<CdoDrug>()
                           {
                               Error = false,
                               Value = drug,
                               InnerMessage = "Sucessfull request on server"
                           };


            }
            catch (Exception ex)
            {
                return new ServiceOut<CdoDrug>()
                {
                    Error = true,
                    InnerMessage = ex.Message.ToString(),
                    Message = new AppMessage()
                                  {
                                   Descr1 = "Problem when try get de information on database"   
                                  }
               };
            }
        }

        public ServiceOut<List<CdoDrug>> EquivalentsLowCostDrugs(AppInteration tInput)
        {
            try
            {
                //Verify the entry parameter
                ResquestIntegretyController.VerifyActionParameter(tInput);
            
                if (tInput.Action != Action.EquivalentLowCost)
                    throw new Exception(String.Format("Action code is wrong, request code action is wrong for this operation. Make the request whit the right action code."));

                List<CdoDrug> drugs = MedicalAdviser.Controllers.DrugOperations.GetEquivalentLowCostDrugs(tInput);
                return new ServiceOut<List<CdoDrug>>()
                {
                    Error = false,
                    Value = drugs,
                    InnerMessage = "Sucessfull request on server"
                };

            }
            catch (Exception ex)
            {
                return new ServiceOut<List<CdoDrug>>()
                {
                    Error = true,
                    InnerMessage = ex.Message.ToString(),
                    Message = new AppMessage()
                    {
                        Descr1 = "Error when try to get Equivalent LowCost drugs for a specific drug "
                    }
                };
            }
        }

        public ServiceOut<List<CdoDrug>> EquivalentMostRecommendationDrugs(AppInteration tInput)
        {
            throw new NotImplementedException();
        }

        public ServiceOut<List<PriceHistory>> PriceVariations(AppInteration tInput)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
